<template>
  <div>
    <!-- 搜索框区域 -->
    <i-search ref="iSearch" :model="formData" @search="fetch" @reset="reset">
      <el-form-item label="商品名称" prop="goodName">
        <el-input v-model="formData.goodName"></el-input>
      </el-form-item>
      <el-form-item label="商品状态" prop="goodStatus">
        <el-select v-model="formData.goodStatus" placeholder="请选择">
          <el-option label="售罄" value="1"></el-option>
          <el-option label="在售" value="2"></el-option>
          <el-option label="已下架" value="3"></el-option>
          <el-option label="未发布" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告词" prop="advertisement">
        <el-input v-model="formData.advertisement"></el-input>
      </el-form-item>
      <el-form-item label="出版社" prop="goodPress">
        <el-input v-model="formData.goodPress"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="goodAuthor">
        <el-input v-model="formData.goodAuthor"></el-input>
      </el-form-item>
    </i-search>

    <!-- 表格区域 -->
    <i-table
      :toolbar="toolbar"
      :tableData="tableData"
      :pageInfo="pageInfo"
      :selectionShow="true"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 表格标题区域 -->
      <el-table-column
        v-for="(item,index) in columnList"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        align="center"
      ></el-table-column>
    </i-table>
    <!-- 新增商品对话框 -->
    <i-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @dialog-before-close="dialogBeforeClose"
      @dialog-cancel="dialogCancel"
      @dialog-confirm="dialogConfirm"
    >
      <el-form :model="dialogFormData" ref="formRef" :rules="formRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodName">
              <el-input v-model="dialogFormData.goodName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书号" prop="goodIsbn">
              <el-input v-model="dialogFormData.goodIsbn"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级分类" prop="firstClass">
              <el-select v-model="dialogFormData.firstClass" placeholder="请选择"
              @change="showFirstClass($event)"
              >
                <el-option v-for="(item,index) in firstClassarr"
                 :label="item.goodClassName" :value="item.goodClassId" :key="index"></el-option>
                
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级分类" prop="secondClass">
               <el-select v-model="dialogFormData.secondClass" placeholder="请选择">
                <el-option v-for="(item,index) in secondClassarr"
                 :label="item.goodClassName" :value="item.goodClassId" :key="index"></el-option>
                
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="广告词" prop="advertisement">
              <el-input
                type="textarea"
                :rows="2"
                v-model="dialogFormData.advertisement"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品描述" prop="goodDetail">
              <el-input
                type="textarea"
                :rows="2"
                v-model="dialogFormData.goodDetail"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="goodAuthor">
              <el-input v-model="dialogFormData.goodAuthor"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="goodStock">
              <el-input v-model="dialogFormData.goodStock"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="成本价" prop="goodPrice">
              <el-input v-model="dialogFormData.goodPrice"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在售价" prop="salePrice">
              <el-input v-model="dialogFormData.salePrice"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出版社" prop="goodPress">
              <el-input v-model="dialogFormData.goodPress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片" prop="picturePath">
              <div class="btn-box">
                点击上传
                <input type="file" id="addfile" @change="inputChange($event)" />
              </div>
              <div class="imginfourl">{{this.dialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>

    <!-- 修改商品会话框 -->
    <i-dialog
      v-model="ChangedialogVisible"
      :title="ChangedialogTitle"
      @dialog-before-close="ChangedialogBeforeClose"
      @dialog-cancel="ChangedialogCancel"
      @dialog-confirm="ChangedialogConfirm"
    >
      <el-form
        :model="ChangedialogFormData"
        ref="ChangeformRef"
        :rules="formRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodName">
              <el-input v-model="ChangedialogFormData.goodName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书号" prop="goodIsbn">
              <el-input v-model="ChangedialogFormData.goodIsbn"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级分类" prop="firstClass">
              <el-select v-model="ChangedialogFormData.firstClass" placeholder="请选择"
              @change="showFirstClass($event)"
              >
                <el-option v-for="(item,index) in firstClassarr"
                 :label="item.goodClassName" :value="item.goodClassId" :key="index"></el-option>
                
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级分类" prop="secondClass">
             <el-select v-model="ChangedialogFormData.secondClass" placeholder="请选择">
                <el-option v-for="(item,index) in secondClassarr"
                 :label="item.goodClassName" :value="item.goodClassId" :key="index"></el-option>
                
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="广告词" prop="advertisement">
              <el-input
                type="textarea"
                :rows="2"
                v-model="ChangedialogFormData.advertisement"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品描述" prop="goodDetail">
              <el-input
                type="textarea"
                :rows="2"
                v-model="ChangedialogFormData.goodDetail"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="goodAuthor">
              <el-input v-model="ChangedialogFormData.goodAuthor"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="goodStock">
              <el-input v-model="ChangedialogFormData.goodStock"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="成本价" prop="goodPrice">
              <el-input v-model="ChangedialogFormData.goodPrice"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在售价" prop="salePrice">
              <el-input v-model="ChangedialogFormData.salePrice"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出版社" prop="goodPress">
              <el-input v-model="ChangedialogFormData.goodPress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片" prop="picturePath">
              <div class="btn-box">
                点击上传
                <input type="file" id="editfile" @change="editinputChange($event)" />
              </div>
              <div class="imginfourl">{{this.ChangedialogFormData.picturePath}}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </i-dialog>
  </div>
</template>

<script>
// 注意首两个字母要大写，这样才会被识别出来所调用的子组件
import ISearch from "../../components/common/i-search.vue";
import ITable from "../../components/common/i-table.vue";
import IDialog from "../../components/common/i-dialog.vue";
import req from "@/api/comm-manager.js";
import axios from "axios";
export default {
  name: "comm-manage",
  data() {
    return {
      // 搜索框数据
      formData: {
        goodName:'',
        advertisement:'',
        goodPress:'',
        goodAuthor:''
      },
      // 新增对话框数据
      dialogFormData: {
        goodName:'',
        goodIsbn:'',
        advertisement:"",
        goodDetail:'',
        goodAuthor:'',
        goodStock:"",
        salePrice:'',
        goodPress:'',
        firstClass:'',
        secondClass:'',
        picturePath:''
      },
      // 修改商品对话框数据对象
      ChangedialogFormData: {},
      // 设置对话框默认为隐藏
      dialogVisible: false,
      // 设置修改商品信息会话框为默认隐藏
      ChangedialogVisible: false,
      // 新增对话框标题
      dialogTitle: "新增商品",
      // 修改会话框的标题
      ChangedialogTitle: "修改商品",
      // 存储选中商品信息的id
      multipId: [],
      // 存储选中商品的状态
      // multipStatus: [],
      // 存储选中商品信息的版本号
      multipVersion: [],
      // 一级商品分类
      firstClassarr:[],
      // 二级分类数据
      secondClassarr:[],
// 一级分类id
firClassId:'',
      // 分页数据
      pageInfo: {
        pageIndex: 1,
        pageSize: 5,
        total: 0
      },
      // 多个按钮数据设置
      toolbar: [
        {
          btnName: "新增",
          type: "primary",
          // 设置按钮的触发事件
          func: () => {
            // 点击新增按钮弹出对话框
            this.dialogVisible = true;
                this.selectGoodClass()
          }
        },
        {
          btnName: "修改",
          type: "primary",
          func: () => {
            if (this.multipId.length === 1) {
              this.ChangedialogVisible = true;
              this.selectGoodClass()
              req("getChangeInfo", {
                goodId: this.multipId[0]
              }).then(data => {
                console.log(data.data.firstClass)
                this.ChangedialogFormData = data.data;
                this.selectSecondClass(data.data.firstClass)
              });
            } 
          }
        },
        {
          btnName: "删除",
          type: "primary",
          func: async () => {
            console.log('id',this.multipId.length)
            if(this.multipId.length!==0){
             const confirmResult = await this.$confirm(
              "此操作将永久删除所选商品, 是否继续?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            ).catch(err => err);
            if (confirmResult !== "confirm") {
              this.$message("已取消删除");
              this.fetch();
            } else {
              req("deleteGoods", {
                goodId: this.multipId.join(",")
              }).then(data => {
                console.log(data)
                if (data.code !== 0) {
                  this.$message.error(data.msg);
                  this.fetch();
                }else{
this.$message.success(data.msg);
                this.fetch();
                }
                
              });
            }
            }
        
            
          }
        },
        {
          btnName: "上架",
          type: "primary",
          func: async () => {
            if(this.multipVersion.length!==0){
             const confirmResult = await this.$confirm(
              "此操作将上架所选商品, 是否继续?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            ).catch(err => err);
            if (confirmResult !== "confirm") {
              this.$message("已取消上架");
              this.fetch();
            } else {
              req("updateGoodStatus", {
                goodId: this.multipId.join(","),
                goodStatus:parseInt(2),
                versionString:this.multipVersion.join(","),
              }).then(data => {
                if (data.code !== 0) {
                  this.$message.error(data.msg);
                  this.fetch();
                }
                this.$message.success(data.msg);
                this.fetch();
              });
            }
            }
            
          }
        },
        {
          btnName: "下架",
          type: "primary",
          func: async () => {
            if(this.multipVersion.length!==0){
              const confirmResult = await this.$confirm(
              "此操作下架所选商品, 是否继续?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            ).catch(err => err);
            if (confirmResult !== "confirm") {
               this.$message("已取消下架");
               this.fetch();
            } else {
              req("updateGoodStatus", {
                goodId: this.multipId.join(","),
                goodStatus:parseInt(3),
                versionString:this.multipVersion.join(","),
              }).then(data => {
                // console.log(data)
                if (data.code !== 0) {
                  return this.$message.error(data.msg);
                  this.fetch();
                }
                this.$message.success(data.msg);
                this.fetch();
              });
            }
            }
            
          }
        }
      ],
      // 表格表头数据
      columnList: [
        { label: "商品名称", prop: "goodName" },
        { label: "定价", prop: "goodPrice" },
        { label: "售价", prop: "salePrice" },
        { label: "销售量", prop: "goodSale" },
        { label: "作者", prop: "goodAuthor" },
        { label: "一级分类", prop: "firstClass" },
        { label: "二级分类", prop: "secondClass" },
        { label: "商品描述", prop: "goodDetail" },
        { label: "商品上架时间", prop: "shelfTime" },
        { label: "广告词", prop: "advertisement" },
        { label: "库存", prop: "goodStock" },
        { label: "书号", prop: "goodIsbn" },
        { label: "出版社", prop: "goodPress" },
        { label: "商品状态", prop: "goodStatus" },
        { label: "星级评分", prop: "starLevel" }
      ],
      // 表格内容数据
      tableData: [],
      formRules: {
        goodName: [
          { required: true, message: "请输入商品名称", trigger: "change" }
        ],
        goodIsbn: [
          { required: true, message: "请输入书号", trigger: "change" }
        ],
        firstClass: [
          { required: true, message: "请选择分类项目", trigger: "change" }
        ],
        secondClass: [
          { required: true, message: "请选择分类项目", trigger: "change" }
        ],
        advertisement: [
          { required: true, message: "请输入广告词", trigger: "change" },
          {
            min: 3,
            max: 55,
            message: "长度在 3 到 55 个字符",
            trigger: "change"
          }
        ],
        goodDetail: [
          { required: true, message: "请输入商品介绍", trigger: "change" },
          {
            min: 3,
            max: 150,
            message: "长度在 3 到 150 个字符",
            trigger: "change"
          }
        ],
        goodStock: [
          { required: true, message: "请输入库存", trigger: "change" },
          
        ],
        salePrice: [
          { required: true, message: "请输入在售价", trigger: "change" },
          
        ],
        goodPrice: [
          { required: true, message: "请输入成本价", trigger: "change" },
          
        ],
        goodsAuthor: [
          { required: true, message: "请输入作者名称", trigger: "change" }
        ],
        goodPress: [
          { required: true, message: "请输入出版社", trigger: "change" }
        ],
        goodAuthor: [
          { required: true, message: "请输入作者", trigger: "change" }
        ]
      }
    };
  },
  // 组件挂载完毕之前加载数据
  mounted() {
    this.fetch();
  },
  methods: {
// 获取选择的一级分类的id
showFirstClass(e){
this.firClassId=e;
this.selectSecondClass()
},
// 新增图片上传
    inputChange(event) {
      let form = new FormData();
      let file = document.getElementById("addfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://d299o16972.qicp.vip/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.dialogFormData.picturePath = data.data.data;
         this.$notify({
          title: '成功',
          message:data.data.msg,
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:data.data.msg,
          type: 'warning'
        });
        }
      });
    },
    // 修改图片上传
    editinputChange(event) {
      let form = new FormData();
      let file = document.getElementById("editfile").files[0];

      form.append("multipartFile", file, file.name);
      axios({
        method: "post",
        url: "http://d299o16972.qicp.vip/pc/image/upload",
        data: form,
        headers: {
          "Content-Type": "Multipart/form-data"
        }
      }).then(data => {
        console.log("data", data);
        if(data.data.code === 0){
this.ChangedialogFormData.picturePath = data.data.data;
         this.$notify({
          title: '成功',
          message:'图片修改成功',
          type: 'success'
        });
        }else{
          this.$notify({
          title: '失败',
          message:'图片修改失败',
          type: 'warning'
        });
        }
        
      });
    },
    fetch() {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 5;
      this.search();
    },
    search() {
      req("getTableData", {
        ...this.formData,
        pageSize: this.pageInfo.pageSize,
        pageNum: this.pageInfo.pageIndex
      }).then(data => {
        console.log(data);
        this.pageInfo.total = data.data.total;
        this.pageInfo.pageSize = data.data.pageSize;
        this.pageInfo.pageNum = data.data.pageNum;
        this.tableData = data.data.list;
        // 商品状态转化为文字
        this.tableData.forEach(item => {
          if (item.goodStatus === 1) {
            item.goodStatus = "售罄";
          } else if (item.goodStatus === 2) {
            item.goodStatus = "在售";
          } else if (item.goodStatus === 3) {
            item.goodStatus = "已下架";
          } else if (item.goodStatus === 4) {
            item.goodStatus = "未发布";
          }
        });
        // 商品上架时间转化
        this.tableData.forEach(item => {
          if (item.shelfTime) {
            const timestamp = item.shelfTime.valueOf()
        const Data = new Date(timestamp)
        const year = Data.getFullYear()
        const month = Data.getMonth() + 1
        const day = Data.getDate()
        // const hours = Data.getHours()
        // const minute = Data.getMinutes()
        // const seconds = Data.getSeconds()
        let time = year + '-' + month + '-' + day
        item.shelfTime = time
          }
        } )
      });
    },
    reset() {
      this.fetch();
    },
    // 每页数据条数
    handleSizeChange(value) {
      this.pageInfo.pageSize = value;
      this.search();
    },
    // 当前页码号
    handleCurrentChange(value) {
      this.pageInfo.pageIndex = value;
      this.search();
    },
    handleSelectionChange(rows) {
      console.log(rows);
      this.multipId = [];
      this.multipVersion = [];
      rows.forEach(item => {
        this.multipId.push(item.goodId);
        this.multipVersion.push(item.version);
      });
    },

    dialogCancel() {
      this.dialogVisible = false;
      this.$refs.formRef.resetFields();
      this.fetch();
    },
    // 点击取消隐藏会话框并清空表单
    ChangedialogCancel() {
      this.ChangedialogVisible = false;
      this.$refs.ChangeformRef.resetFields();
      this.fetch();
    },
    ChangedialogBeforeClose(){
this.ChangedialogVisible = false;
      this.$refs.ChangeformRef.resetFields();
      this.fetch();
    },

    // 在表单关闭之前清空表单填写的数据
    dialogBeforeClose() {
      this.$refs.formRef.resetFields();
      this.dialogVisible = false;
      this.fetch();
    },
    // 新增对话框确认上传数据
    dialogConfirm() {
      // 测试新增数据的类型
      // console.log(typeof this.dialogFormData.goodStcok)
      // console.log(typeof this.dialogFormData.goodPrice)
      // console.log(typeof this.dialogFormData.salePrice)
      // this.dialogFormData.goodStcok=parseInt(this.dialogFormData.goodStcok)
      // this.dialogFormData.goodPrice=parseFloat(this.dialogFormData.goodPrice)
      // this.dialogFormData.salePrice=parseFloat(this.dialogFormData.salePrice)

      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        req("addGoods", {
          access_token: JSON.parse(sessionStorage.getItem("userInfo"))
            .access_token,
          ...this.dialogFormData
        }).then(data => {
          // console.log(data)
          if (data.code !== 0) {
            this.$message.error(data.msg);
            this.fetch();
          } else {
            this.$message.success(data.msg);
            this.fetch();
          }
          // 隐藏对话框
          this.dialogVisible = false;
          // 刷新页面
          this.fetch();
        });
      });
    },
    // 点击确认按钮修改商品信息
    ChangedialogConfirm() {
      req("editGoodInfo", {
        ...this.ChangedialogFormData,
        goodId: this.multipId[0]
      }).then(data => {
        console.log(data);
 if (data.code === 0) {
          this.$message.success(data.msg);
          this.fetch();
          this.ChangedialogVisible = false;
        }else{
          this.$message.error(data.msg)
          this.fetch();
          this.ChangedialogVisible = false;
        }
      });
    },
    // 获取商品一级分类
    selectGoodClass(){
      req("selectGoodClass",{}).then(data=>{
        console.log(data)
        this.firstClassarr=data.data
      })
    },
    // 获取二级分类
    selectSecondClass(number){
      if(number){
req("selectGoodClass",{
        goodClassId:number
      }).then(data=>{
        console.log('erji',data)
        this.secondClassarr=data.data
      })
      }
      req("selectGoodClass",{
        goodClassId:this.firClassId
      }).then(data=>{
        console.log(data)
        this.secondClassarr=data.data
      })
      
    },
  },
  // 子组件注册
  components: {
    ISearch,
    ITable,
    IDialog
  }
};
</script>

<style lang="scss" scoped>
.el-input{
  width: 218px;
}
</style>
